import {
  ads_sc,
  task_wait,
  task_report,
  account_maintenance_task_report,
} from "@/api/xhs";

export const handlePython = async () => {
  try {
    const res = await ads_sc();
    if (res.code === 0) {
      localStorage.setItem("pythons", JSON.stringify(res.data));
      window.electronAPI.downPythons(res.data);
    }
  } catch (err) {
    console.log(err);
  }
};

// 启动浏览器并执行脚本
const openBrowser = async (ads_power, headless, task, key, filename) => {
  const user = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user"))
    : undefined;
  if (!(user && user.userInfo && user.userInfo.token)) retrun;
  const { ads_power_id, xhs_user_id } = ads_power;
  const start_result = await window.electronAPI.fetch(
    `http://local.adspower.net:50325/api/v1/browser/start?user_id=${encodeURIComponent(
      ads_power_id
    )}&ip_tab=0&open_tabs=1&headless=${headless}`,
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    }
  );
  if (!start_result.data) return;
  const { ws, webdriver } = start_result.data;
  const {
    images,
    comment,
    text,
    title,
    videos,
    collect_limit,
    collect_rate,
    comment_limit,
    comment_rate,
    comments,
    keywords,
    like_limit,
    like_rate,
  } = task.config;
  const { duration, id } = task;
  console.log("ads_power", ads_power);
  let args;
  console.log("key", key);
  switch (key) {
    case "c":
      args = [
        `'${ws.selenium}'`,
        `'${webdriver}'`,
        `'${images.join(",")}'`,
        `'${title}'`,
        `'${text}'`,
        `'${comment}'`,
      ];
      break;
    case "c_win":
      args = [
        `"${ws.selenium}"`,
        `"${webdriver}"`,
        `"${images.join(",")}"`,
        `"${title}"`,
        `"${text}"`,
        `"${comment}"`,
      ];
      break;
    case "d":
      args = [
        `'${ws.selenium}'`,
        `'${webdriver}'`,
        `'${videos.join(",")}'`,
        `'${title}'`,
        `'${text}'`,
        `'${comment}'`,
      ];
      break;
    case "d_win":
      args = [
        `"${ws.selenium}"`,
        `"${webdriver}'`,
        `"${videos.join(",")}"`,
        `"${title}"`,
        `"${text}"`,
        `"${comment}"`,
      ];
      break;
    case "e":
      args = [`'${ws.selenium}'`, `'${webdriver}'`];
      break;
    case "e_win":
      args = [`"${ws.selenium}"`, `"${webdriver}"`];
      break;
    case "f":
      args = [
        `'${ws.selenium}'`,
        `'${webdriver}'`,
        `'${keywords.join(",")}'`,
        `'${comments.join(",")}'`,
        `'${like_limit}'`,
        `'${like_rate}'`,
        `'${collect_limit}'`,
        `'${collect_rate}'`,
        `'${comment_limit}'`,
        `'${comment_rate}'`,
        `'${duration}'`,
        `'${user.userInfo.token}'`,
        `'${id}'`,
      ];
      break;
    case "f_win":
      args = [
        `"${ws.selenium}"`,
        `"${webdriver}"`,
        `"${keywords.join(",")}"`,
        `"${comments.join(",")}"`,
        `"${like_limit}"`,
        `"${like_rate}"`,
        `"${collect_limit}"`,
        `"${collect_rate}"`,
        `"${comment_limit}"`,
        `"${comment_rate}"`,
        `"${duration}"`,
        `"${user.userInfo.token}"`,
        `"${id}"`,
      ];
      break;
  }
  const pythons = localStorage.getItem("pythons")
    ? JSON.parse(localStorage.getItem("pythons"))
    : {};
  const downloadUrl = pythons[key];
  console.log("download_args", args);
  console.log("任务执行命令", `${downloadUrl} ${args.join(" ")}`);
  const result = await window.electronAPI.downloadAndExecute(
    downloadUrl,
    args,
    filename
  );
  console.log("------", result);
  const new_result = JSON.parse(result);
  console.log("------new_result", new_result);
  // 非养号上报任务
  const maintenances = ["f", "f_win"];
  if (new_result.code !== 0 && maintenances.indexOf(key) === -1) {
    await task_report({
      status: 0,
      is_finish: false,
      reason: result,
      task_id: task.id,
      xhs_user_id,
    });
  }
  console.log("new_result", new_result);
  if (new_result.code === 0 && maintenances.indexOf(key) === -1) {
    await task_report({
      status: 1,
      is_finish: true,
      note_id: new_result.data.noteId,
      task_id: task.id,
      xhs_user_id,
    });
  }
  // 养号执行上报任务
  if (maintenances.indexOf(key) !== -1) {
    await account_maintenance_task_report({
      id: task.id,
    });
  }
  await window.electronAPI.fetch(
    `http://local.adspower.net:50325/api/v1/browser/stop?user_id=${encodeURIComponent(
      ads_power_id
    )}`,
    {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    }
  );
};

const isWindows = () => {
  return navigator.userAgent.indexOf("Win") !== -1;
};
export const republishTask = async () => {
  try {
    const wait_data = await task_wait();
    if (wait_data.code === 0) {
      const { tasks } = wait_data.data;
      console.log("待执行任务", wait_data);
      if (!tasks) return;
      for (let i = 0; i < tasks.length; i++) {
        const task = tasks[i];
        const { ads_powers } = task;
        console.log("ads_powers", ads_powers);
        for (let j = 0; j < ads_powers.length; j++) {
          const { ads_power_id } = ads_powers[j];
          console.log("ads_power_id", ads_power_id);
          const keys = {
            0: "c",
            1: "d",
            2: "e",
            3: "f",
          };
          let key = keys[task.type_int];
          const exact_key = isWindows() ? "_win" : "";
          const pyjs = {
            0: `${key}${exact_key}_image_publish`,
            1: `${key}${exact_key}_video_publish`,
            2: `${key}${exact_key}_note_data`,
            3: `${key}${exact_key}_account_maintenance`,
          };
          let filename = pyjs[task.type_int];
          console.log("ads_power_id", key, filename);
          try {
            await openBrowser(
              ads_powers[j],
              1,
              task,
              `${key}${exact_key}`,
              filename
            );
          } catch (err) {
            // 脚本执行异常关闭浏览器
            await window.electronAPI.fetch(
              `http://local.adspower.net:50325/api/v1/browser/stop?user_id=${encodeURIComponent(
                ads_power_id
              )}`,
              {
                method: "GET",
                headers: {
                  "Content-Type": "application/json",
                },
              }
            );
          }
        }
      }
    }
  } catch (err) {
    console.log(err);
  }
};
